package com.wad.security.impl;

import com.wad.enums.KeyEnums;
import com.wad.common.ResponseResult;
import com.wad.domain.User;
import com.wad.encrypt.AESUtil;
import com.wad.mapper.UserMapper;
import com.wad.redis.RedisCache;
import com.wad.security.LoginService;
import com.wad.security.LoginUser;
import com.wad.utlis.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wad
 * @date 2022/11/12 15:07
 * @project JWT_DEMO2
 **/
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserMapper userMapper;

//    登录实现
    @Override
    public ResponseResult login(User user) throws Exception {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        if (authenticate == null){
            throw new RuntimeException("用户名或密码错误");
        }
//        使用userid生成token
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
//        对userId进行了AES对称加密处理，保证token被截获时的安全性
        byte[] encrypt = AESUtil.encrypt(userid.getBytes(), KeyEnums.SECRETKEY.devKey.getCodeKey().getBytes());
        String userId= Arrays.toString(encrypt);
        //生成Jwt令牌
        Map<String,String> payload=new HashMap<>();
        payload.put("userId",userId);
        String jwtToken = JWTUtil.getToken(payload);
//        将authenticate存入redis中
        redisCache.setCacheObjct("login:"+userId,loginUser);
//        将token响应给前端
        Map<String,String> tokenMap=new HashMap<>();
        tokenMap.put("token",jwtToken);
        return new ResponseResult<>(200,"登录成功",tokenMap);
    }

//    退出实现
    public ResponseResult logout(){
//        从SecurityContextHolder中获取用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser=(LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
//        从redis中删除对应用户id的用户信息
        redisCache.deleteObject("login:"+id);
        return new ResponseResult(200,"退出成功");
    }


    @Override
    public ResponseResult register(User user) {
//        对密码的长度进行限制不少于6位
        if (user.getPassword().length()<6){
            return new ResponseResult(500,"密码不能小于6位");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        int register = userMapper.insertUserForRegister(user);
//        根据注册的姓名查找新增人员
        User userInfoByUserName = userMapper.selectUserInfoByUserName(user.getUserName());
        if (register >0 && userInfoByUserName !=null){
            return new ResponseResult(200,"注册成功",userInfoByUserName);
        }
        return new ResponseResult(500,"注册失败");
    }
}
